package com.gx.mvp.net;

import android.content.Context;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by Guoxin on 2019-12-07.
 */
public abstract class ApiSubscriber<T> implements Observer<T> {

    private Context mContext;

    public ApiSubscriber(Context mContext) {
        this.mContext = mContext;
    }

    protected abstract void onSuccess(T t);

    protected abstract void onError(String errorMessage);

    protected abstract void register(Disposable d);

    @Override
    public void onNext(T t) {
        this.onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof UnknownHostException) {
            onError("服务器异常，请稍后再试");
        }
        else if (e instanceof SocketTimeoutException) {
            onError("服务器连接超时，请稍后再试");
        }
        else if (e instanceof ApiException) {
            ApiException apiException = (ApiException) e;
            onError(apiException.getErrorMessage());
            return;
        }
        else{
            onError(e.getMessage());
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        register(d);
    }

    @Override
    public void onComplete() {

    }
}
